// const WebSocket = require('ws');



// import WebSocket from 'ws';
let ws = null; //;= new WebSocket('ws://192.168.0.155:30080/statelistening');
let isopen = false;
let lastrequestDevicetime = Date.now();
let deviceObj = [];
let timeoutVal = null;
let reccount = 1;
const hostname = window.location.hostname; // 返回主机名部分
const port = window.location.port; // 返回端口号

// console.log('hostname', hostname);
// const hostname = '192.168.0.106'
console.log('hostname', hostname);
console.log('port', port);

export const init = () => {
  try {
    ws = new WebSocket(`ws://${hostname}/statelistening`);
    ws.onopen = () => {
      ws.send('login');
      isopen = true;
      console.log('ws.readyState', ws.readyState);
      if (ws.readyState == 1) {
        console.log('WebSocket连接成功...');
        setInterval(function ping() {
          if (isopen) {
            ws.send('heartbeat');
          }
        }, 3000);
      } else {
        console.log('WebSocket重连中...');
        init();
      }
    };
  } catch (error) {
    console.log('err', error);
  }
};
export const onmessage = (cb) => {
  ws.onmessage = async (e) => {
    // console.log(e.data);
    // if (ws.readyState == 1) {
    //   console.log('WebSocket实时更新...');
    // }

    if (ws.readyState == 0) {
      init();
    }
    // cb(e.data);

    if (e.data !== 'HeartBeat') {
      FucServerDeviceInfoChanged();
      cb(e.data);
    }
  };
};
export const onclose = () => {
  console.log('关闭');
  ws.onclose = async () => {
    console.log('ws close');
    isopen = false;
    ws = null;
    setTimeout(function () {
      init();
    }, 3000);
  };
};

export const FucServerDeviceInfoChanged = () => {
  let now = Date.now();
  if (now - lastrequestDevicetime > 500) {
    lastrequestDevicetime = now;
  } else {
    clearTimeout(timeoutVal);
    timeoutVal = setTimeout(function () {
      FucServerDeviceInfoChanged();
    }, 200);
  }
};

// init();
